package com.taskmanager.service;

import com.taskmanager.dao.CategoryDao;
import com.taskmanager.dto.CategoryRequest;
import com.taskmanager.dto.CategoryResponse;
import com.taskmanager.entity.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 分类业务逻辑层
 */
@Service
public class CategoryService {
    
    @Autowired
    private CategoryDao categoryDao;
    
    @Autowired
    private TaskService taskService;
    
    /**
     * 为新用户创建默认分类
     * @param userId 用户ID
     */
    @Transactional(rollbackFor = Exception.class)
    public void createDefaultCategories(Long userId) {
        List<Category> defaultCategories = new ArrayList<>();
        
        // 工作
        Category work = new Category();
        work.setUserId(userId);
        work.setName("工作");
        work.setColor("#FF5733");
        work.setIsDefault(1);
        defaultCategories.add(work);
        
        // 学习
        Category study = new Category();
        study.setUserId(userId);
        study.setName("学习");
        study.setColor("#33FF57");
        study.setIsDefault(1);
        defaultCategories.add(study);
        
        // 生活
        Category life = new Category();
        life.setUserId(userId);
        life.setName("生活");
        life.setColor("#3357FF");
        life.setIsDefault(1);
        defaultCategories.add(life);
        
        // 其他
        Category other = new Category();
        other.setUserId(userId);
        other.setName("其他");
        other.setColor("#999999");
        other.setIsDefault(1);
        defaultCategories.add(other);
        
        // 批量插入
        categoryDao.batchInsert(defaultCategories);
    }
    
    /**
     * 查询用户的所有分类（包含任务数量）
     * @param userId 用户ID
     * @return 分类列表
     */
    public List<CategoryResponse> getCategoriesByUserId(Long userId) {
        List<Category> categories = categoryDao.selectByUserIdWithTaskCount(userId);
        
        return categories.stream().map(category -> {
            CategoryResponse response = new CategoryResponse();
            response.setCategoryId(category.getCategoryId());
            response.setName(category.getName());
            response.setColor(category.getColor());
            response.setTaskCount(category.getTaskCount() != null ? category.getTaskCount() : 0);
            return response;
        }).collect(Collectors.toList());
    }
    
    /**
     * 创建新分类
     * @param userId 用户ID
     * @param request 分类请求
     * @return 分类响应
     */
    @Transactional(rollbackFor = Exception.class)
    public CategoryResponse createCategory(Long userId, CategoryRequest request) {
        // 检查分类名称是否已存在
        Category existing = categoryDao.selectByUserIdAndName(userId, request.getName());
        if (existing != null) {
            throw new IllegalArgumentException("分类名称已存在");
        }
        
        // 创建分类
        Category category = new Category();
        category.setUserId(userId);
        category.setName(request.getName());
        category.setColor(request.getColor() != null ? request.getColor() : "#999999");
        category.setIsDefault(0);
        
        int result = categoryDao.insert(category);
        if (result <= 0) {
            throw new RuntimeException("创建分类失败");
        }
        
        // 返回响应
        CategoryResponse response = new CategoryResponse();
        response.setCategoryId(category.getCategoryId());
        response.setName(category.getName());
        response.setColor(category.getColor());
        response.setTaskCount(0);
        
        return response;
    }
    
    /**
     * 更新分类
     * @param userId 用户ID
     * @param categoryId 分类ID
     * @param request 分类请求
     * @return 分类响应
     */
    @Transactional(rollbackFor = Exception.class)
    public CategoryResponse updateCategory(Long userId, Long categoryId, CategoryRequest request) {
        // 验证分类所有权
        if (!categoryDao.belongsToUser(categoryId, userId)) {
            throw new IllegalArgumentException("无权操作此分类");
        }
        
        // 检查新名称是否与其他分类重复
        Category existing = categoryDao.selectByUserIdAndName(userId, request.getName());
        if (existing != null && !existing.getCategoryId().equals(categoryId)) {
            throw new IllegalArgumentException("分类名称已存在");
        }
        
        // 更新分类
        Category category = new Category();
        category.setCategoryId(categoryId);
        category.setName(request.getName());
        category.setColor(request.getColor());
        
        int result = categoryDao.update(category);
        if (result <= 0) {
            throw new RuntimeException("更新分类失败");
        }
        
        // 查询更新后的分类
        Category updated = categoryDao.selectById(categoryId);
        int taskCount = categoryDao.countTasksByCategoryId(categoryId);
        
        CategoryResponse response = new CategoryResponse();
        response.setCategoryId(updated.getCategoryId());
        response.setName(updated.getName());
        response.setColor(updated.getColor());
        response.setTaskCount(taskCount);
        
        return response;
    }
    
    /**
     * 删除分类
     * @param userId 用户ID
     * @param categoryId 分类ID
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteCategory(Long userId, Long categoryId) {
        // 验证分类所有权
        if (!categoryDao.belongsToUser(categoryId, userId)) {
            throw new IllegalArgumentException("无权操作此分类");
        }
        
        // 获取"其他"分类
        Category otherCategory = categoryDao.selectOtherCategory(userId);
        if (otherCategory == null) {
            throw new RuntimeException("未找到'其他'分类");
        }
        
        // 不能删除"其他"分类
        if (categoryId.equals(otherCategory.getCategoryId())) {
            throw new IllegalArgumentException("不能删除'其他'分类");
        }
        
        // 将该分类下的所有任务移至"其他"分类
        taskService.moveTasksCategoryToOther(categoryId, otherCategory.getCategoryId());
        
        // 删除分类
        int result = categoryDao.deleteById(categoryId);
        if (result <= 0) {
            throw new RuntimeException("删除分类失败");
        }
    }
    
    /**
     * 根据ID获取分类
     * @param categoryId 分类ID
     * @return 分类对象
     */
    public Category getCategoryById(Long categoryId) {
        Category category = categoryDao.selectById(categoryId);
        if (category == null) {
            throw new IllegalArgumentException("分类不存在");
        }
        return category;
    }
}
